package com.webchat.client.payment.service;

import com.webchat.common.constants.CookieConstants;
import com.webchat.common.enums.RedisKeyEnum;
import com.webchat.common.service.RedisService;
import com.webchat.common.util.DateUtils;
import com.webchat.common.util.MD5Utils;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserSessionService {

    @Autowired
    private RedisService redisService;

    public String getUserIdByRequest(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (CookieConstants.WEB_CHAT_PAYMENT_USER_COOKIE_KEY.equals(cookie.getName())) {
                    String sessionId = cookie.getValue();
                    return this.getUserIdBySessionId(sessionId);
                }
            }
        }
        return null;
    }

    public void logout(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (CookieConstants.WEB_CHAT_CLIENT_USER_COOKIE_KEY.equals(cookie.getName())) {
                    String sessionId = cookie.getValue();
                    this.deleteUserLoginSession(sessionId);
                }
            }
        }
    }

    public void createUserLoginSession(HttpServletResponse response, String userId) {
        String sessionId = MD5Utils.md5(userId + DateUtils.getCurrentFormatDate());
        this.setUserIdBySessionId(sessionId, userId);
        // 种浏览器Cookie
        Cookie cookie = new Cookie(CookieConstants.WEB_CHAT_CLIENT_USER_COOKIE_KEY, sessionId);
        cookie.setPath("/");
        cookie.setMaxAge(CookieConstants.COOKIE_OUT_TIME);
        response.addCookie(cookie);
    }

    private void deleteUserLoginSession(String sessionId) {
        String sessionCacheKey = RedisKeyEnum.USER_SESSION_PREFIX.getKey(sessionId);
        redisService.remove(sessionCacheKey);
    }

    public String getUserIdBySessionId(String sessionId) {
        String sessionCacheKey = RedisKeyEnum.USER_SESSION_PREFIX.getKey(sessionId);
        return redisService.get(sessionCacheKey);
    }

    public void setUserIdBySessionId(String sessionId, String userId) {
        String sessionCacheKey = RedisKeyEnum.USER_SESSION_PREFIX.getKey(sessionId);
        redisService.set(sessionCacheKey, userId, RedisKeyEnum.USER_SESSION_PREFIX.getExpireTime());
    }
}
